<?php
namespace app\controller;

use app\BaseController;
use app\service\PointsService;
use think\facade\Db;
use think\facade\Validate;
use app\middleware\AuthMiddleware;
use think\App;

class Points extends BaseController
{
    protected $middleware = [AuthMiddleware::class];
    protected $pointsService;

    public function __construct(App $app, PointsService $pointsService)
    {
        parent::__construct($app);
        $this->pointsService = $pointsService;
    }

    // 查询积分
    public function getUserPoints()
    {
        $userId = $this->request->user->uid;
        $pointsService = app(PointsService::class);
        $points = $pointsService->getUserPoints($userId);
        return json(['code' => 200, 'data' => ['points' => $points]]);
    }

    // 充值下单
    public function createOrder()
    {
        $userId = $this->request->user->uid;
        $points = $this->request->post('points');
        $amount = $this->request->post('amount');
        $payType = $this->request->post('payType', 'alipay');
        $orderNo = 'PO' . date('YmdHis') . rand(1000, 9999);
        $orderId = Db::name('points_order')->insertGetId([
            'user_id' => $userId,
            'order_no' => $orderNo,
            'amount' => $amount,
            'points' => $points,
            'status' => 0,
            'pay_type' => $payType,
            'create_time' => time()
        ]);
        // 这里应返回支付二维码/链接，暂返回订单号
        return json(['code' => 200, 'data' => ['order_no' => $orderNo, 'order_id' => $orderId]]);
    }

    // 支付回调（示例，实际应做签名校验）
    public function payCallback()
    {
        $orderNo = $this->request->post('order_no');
        $order = Db::name('points_order')->where('order_no', $orderNo)->find();
        if (!$order || $order['status'] != 0) return json(['code' => 400, 'msg' => '订单不存在或已处理']);
        Db::startTrans();
        try {
            Db::name('points_order')->where('id', $order['id'])->update([
                'status' => 1,
                'pay_time' => time()
            ]);
            $pointsService = app(PointsService::class);
            $pointsService->recharge($order['user_id'], $order['points'], $order['id']);
            Db::commit();
            return json(['code' => 200, 'msg' => '充值成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }

    // 积分流水
    public function log()
    {
        $userId = $this->request->user->uid;
        $list = Db::name('points_log')
            ->field('id, user_id, type, change as points, balance, remark as description, create_time')
            ->where('user_id', $userId)
            ->order('id desc')
            ->limit(100)
            ->select()
            ->each(function($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                return $item;
            });
        return json(['code' => 200, 'data' => $list]);
    }

    /**
     * 获取用户积分明细
     */
    public function getPointsLogs()
    {
        try {
            $userId = $this->request->user->uid;
            $page = $this->request->param('page/d', 1);
            $pageSize = $this->request->param('pageSize/d', 10);
            $type = $this->request->param('type');
            $startDate = $this->request->param('startDate');
            $endDate = $this->request->param('endDate');

            // 验证日期格式
            if ($startDate && !strtotime($startDate)) {
                return json(['code' => 400, 'msg' => '开始日期格式错误']);
            }
            if ($endDate && !strtotime($endDate)) {
                return json(['code' => 400, 'msg' => '结束日期格式错误']);
            }

            // 验证类型
            if ($type && !in_array($type, ['recharge', 'consume'])) {
                return json(['code' => 400, 'msg' => '类型错误']);
            }

            $result = $this->pointsService->getPointsLogs(
                $userId,
                $page,
                $pageSize,
                $type,
                $startDate,
                $endDate
            );

            return json(['code' => 200, 'msg' => 'success', 'data' => $result]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取用户积分统计
     */
    public function getPointsStats()
    {
        try {
            $userId = $this->request->user->uid;
            $startDate = $this->request->param('startDate');
            $endDate = $this->request->param('endDate');

            // 验证日期格式
            if ($startDate && !strtotime($startDate)) {
                return json(['code' => 400, 'msg' => '开始日期格式错误']);
            }
            if ($endDate && !strtotime($endDate)) {
                return json(['code' => 400, 'msg' => '结束日期格式错误']);
            }

            $result = $this->pointsService->getPointsStats(
                $userId,
                $startDate,
                $endDate
            );

            return json(['code' => 200, 'msg' => 'success', 'data' => $result]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取用户当前积分
     */
    public function getCurrentPoints()
    {
        try {
            $userId = $this->request->user->uid;
            $points = $this->pointsService->getUserPoints($userId);
            return json(['code' => 200, 'msg' => 'success', 'data' => ['points' => $points]]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }
} 